$(function () {
    initDatagrid();

    $("#queryButton").click(function () {
        $("#listTable1").datagrid('load', {
            verifyResult: $("#verifyResult").combobox('getValue'),
            queryStr: $("#queryStr").val(),
            createTime: $("input[name=createTime]").val()
        })
    });
});

// 商品展示列表
function initDatagrid() {
    var url = $.util.getRequestJson('/json/productManage.productList.json');
    $('#listTable1').datagrid({
        // type=0 即查询 普通公告类型数据
        url: url /*+ '?type=0'*/,
        idField: 'id',
        queryParams: {
            groupType: "commodity"
        },
        fit: true,
        pagination: true,
        pageSize: 30,
        checkOnSelect: false,
        selectOnCheck: false,
        singleSelect: true,
        toolbar: '#toolbarButton',
        fitColumns: true,
        columns: [
            [
                /*{
                    field: 'id',
                    title: '商品编号',
                    align: 'center',
                    width: 20
                },*/
                {
                    field: 'title',
                    title: '商品名称'
                },
                /*{
                    field: 'marketPrice',
                    title: '价格',
                    align: 'center',
                    width: 12
                },*/
                {
                    field: 'needScore',
                    title: '兑换所需积分',
                    align: 'center',
                    width: 10,
                    formatter: function (value, row) {
                        return value == null ? "——" : value;
                    }
                },
                /*{
                    field: 'dictText',
                    title: '所属分类',
                    align: 'center',
                    width: 25
                },
                {
                    field: 'name',
                    title: '所属店铺',
                    align: 'center',
                    width: 18,
                    formatter: function (value, row) {
                        return value == null ? "——" : value;
                    }
                },*/
                {
                    field: 'createTime',
                    title: '创建时间',
                    align: 'center',
                    width: 20
                },
                {
                    field: 'realName',
                    title: '审核人',
                    align: 'center',
                    width: 15,
                    formatter: function (value, row) {
                        return value == null ? "——" : value;
                    }
                },
                {
                    field: 'verifyResult',
                    title: '审核状态',
                    align: 'center',
                    width: 12,
                    formatter: function (value, row) {
                        //return value == null ? "待审核":value;
                        if (value == '0') {
                            return "<font color='red'>未通过</font>"
                        } else if (value == '1') {
                            return "<font color='green'>已通过</font>"
                        } else {
                            return "待审核"
                        }
                    }
                },
                {
                    field: 'status',
                    title: '商品状态',
                    align: 'center',
                    width: 12,
                    formatter: function (value, row) {
                        //return value == null ? "待审核":value;
                        if (value == '0') {
                            return "待上架"
                        } else if (value == '1') {
                            return "<font color='green'>已上架</font>"
                        } else if (value == '2') {
                            return "<font color='red'>已下架</font>"
                        }
                    }
                },
                {
                    field: 'context',
                    align: 'center',
                    width: 20,
                    title: '操作',
                    formatter: function (value, row, index) {
                        var aEl = '<a href=javascript:findDetail("{0}","{1}"); class="easyui-tooltip" title="查看">查看</a>' +
                            ' | <a href=javascript:editProduct("{0}"); class="easyui-tooltip" title="编辑">编辑</a>' +
                            ' | <a href=javascript:editPrice("{0}"); class="easyui-tooltip" title="调整价格">调整价格</a>';
                        if (row.verifyResult == '1') {
                            if (row.status == '0' || row.status == '2') {
                                aEl += ' | <a href=javascript:upProduct("{0}"); class="easyui-tooltip" title="上架">上架</a>';
                            } else if (row.status == '1') {
                                aEl += ' | <a href=javascript:downProduct("{0}"); class="easyui-tooltip" title="下架">下架</a>';
                            }
                        }
                        if (row.status == '0' || row.status == '2') {
                            aEl += ' | <a href=javascript:deleteProduct("{0}"); class="easyui-tooltip" title="删除">删除</a>';
                        }

                        //格式化操作按钮
                        return $.string.format(aEl, row.id,index);
                    }
                }
            ]
        ]
    });
}

// 商品新增
function commAdd() {
    var title = "商品新增";
    var url = $.util.getRootPath() + '/page/productManage/productAdd.html';
    //url = id ? url + '?id=2&typeId=' + typeId : url;
    var dialog = $.easyui.showDialog({
        iconCls: "",
        title: title,
        width: 800,
        height: 600,
        maximizable: true,
        href: url,
        topMost: true,
        saveButtonText: '新增',
        onSave: function () {
            subForm(dialog);
        }
    });
}

// 商品详情
function findDetail(id,index) {
    var title = "商品详情";
    var url = $.util.getRootPath() + '/page/productManage/productDetail.html?id=' + id;
    //url = id ? url + '?id=2&typeId=' + typeId : url;
    if(index == ""){
        index = 0;
    }
    var status = $("#listTable1").datagrid('getRows')[index].status;
    var buttons;
    if(status == 2){
        buttons = [
            {
                id : "flagBttOne",
                text : " ↑ 上架",
                handler : function() {
                    upProduct(id);
                }
            },
            {
                text : "删 除",
                handler : function() {
                    deleteProduct(id);
                }
            }
        ]
    }else if(status == 1){
        buttons = [
            {
                id : "flagBttTwo",
                text : " ↓ 下架",
                handler : function() {
                    downProduct(id);
                }
            }
        ]
    }else{
        buttons = [
            {
                text : "删 除",
                handler : function() {
                    deleteProduct(id);
                }
            }
        ]
    }
    var dialog = $.easyui.showDialog({
        iconCls: "",
        title: title,
        width: 800,
        height: 600,
        maximizable: true,
        href: url,
        topMost: true,
        enableSaveButton: false,
        buttons: buttons,
        closeButtonText: '关闭'
    });
}

// 商品删除
function deleteProduct(id) {
    parent.$.messager.confirm('确认对话框', '您确定要删除该商品吗？', function (r) {
        if (r) {
            //var deleteUrl = "/json/commodity.deleteById.json";
            var url = $.util.getRequestJson('/json/productManage.deleteProduct.json');
            $.util.get(url, {id: id}, function (res) {
                // 删除完成重新加载
                if (res.success) {
                    $('#listTable1').datagrid('reload');
                }
                $.easyui.messager.show(res.message);
            });
        }
    });
}

// 商品上架
function upProduct(id) {
    parent.$.messager.confirm('确认对话框', '您确定要上架该商品吗？', function (r) {
        if (r) {
            var url = $.util.getRequestJson('/json/productManage.updateProduct.json');
            $.util.get(url, {id: id, status: 1}, function (res) {
                // 上架完成重新加载
                if (res.success) {
                    $('#listTable1').datagrid('reload');
                }
                $.easyui.messager.show(res.message);
            });
        }
    });
}

// 商品下架
function downProduct(id) {
    parent.$.messager.confirm('确认对话框', '您确定要下架该商品吗？', function (r) {
        if (r) {
            var url = $.util.getRequestJson('/json/productManage.updateProduct.json');
            $.util.get(url, {id: id, status: 2}, function (res) {
                // 上架完成重新加载
                if (res.success) {
                    $('#listTable1').datagrid('reload');
                }
                $.easyui.messager.show(res.message);
            });
        }
    });
}

// 商品编辑
function editProduct(id) {
    var title = "商品编辑";
    var url = $.util.getRootPath() + '/page/productManage/productAdd.html';
    url = url + '?id=' + id;
    var dialog = $.easyui.showDialog({
        iconCls: "",
        title: title,
        width: 800,
        height: 600,
        maximizable: true,
        href: url,
        topMost: true,
        saveButtonText: '保存',
        onSave: function () {
            subForm(dialog);
        }
    });
}

// 调整价格
function editPrice(id) {
    var title = "调整价格";
    var url = $.util.getRootPath() + '/page/productManage/productEdit.html';
    url = url + '?id=' + id;
    var dialog = $.easyui.showDialog({
        iconCls: "",
        title: title,
        width: 600,
        height: 400,
        maximizable: true,
        href: url,
        topMost: true,
        saveButtonText: '确定',
        onSave: function () {
            subForm1(dialog);
        }
    });
}

// 调整价格保存
function subForm1(dialog) {
    var marketPrice = parent.$("#marketPrice").val();
    var needScore = parent.$("#needScore").val();
    var discountPrice = parent.$("#discountPrice").val();
    var discountScore = parent.$("#discountScore").val();
    var attributePrice = parent.$('#disPrice').attr('style');
    var attributeScore = parent.$('#disScore').attr('style');
    if (!/^(0|([1-9]\d*))(\.\d+)?$/.test(marketPrice) || marketPrice.length>18) {
        parent.$.messager.alert('请正确输入商品价格');
        return;
    }
    if (!/^[0-9]*$/.test(needScore) || needScore.length>9) {
        parent.$.messager.alert('请正确输入兑换积分');
        return;
    }
    if (!attributePrice) {
        if (discountPrice == "" || discountPrice == null) {
            parent.$.messager.alert('请输入优惠价格');
            return;
        } else {
            if (!/^(0|([1-9]\d*))(\.\d+)?$/.test(discountPrice) || discountPrice.length>18) {
                parent.$.messager.alert('请正确输入优惠价格');
                return;
            }
        }
    }
    if (!attributeScore) {
        if (discountScore == "" || discountScore == null) {
            parent.$.messager.alert('请输入优惠兑换积分');
            return;
        } else {
            if (!/^[0-9]*$/.test(discountScore) || discountScore.length>9) {
                parent.$.messager.alert('请正确输入优惠兑换积分');
                return;
            }
        }
    }

    var url = $.util.getRootPath() + '/productManage/editPrice';
    var form = parent.$('#productEdit').form('submit', {
        url: url,
        onSubmit: function () {
            return parent.$('#productEdit').form('validate');
        },
        success: function (data) {
            if (data.success) {
                $('#listTable1').datagrid('reload');
                dialog.dialog('close');
            }
            $.easyui.messager.show(data.message);
        }
    });
}

// 商品保存
function subForm(dialog) {
    var commtityType = parent.$("#commtityType").combobox('getValues');
    var marketPrice = parent.$("#marketPrice").val();
    var needScore = parent.$("#needScore").val();
    var discountPrice = parent.$("#discountPrice").val();
    var discountScore = parent.$("#discountScore").val();
    var title = parent.$("#title").val();
    var id = parent.$("#id").val();
    var attachedFile = parent.$("#attachedFile").val();
    var attributePrice = parent.$('#disPrice').attr('style');
    var attributeScore = parent.$('#disScore').attr('style');
    if (title.length > 100) {
        parent.$.messager.alert('商品名称过长');
        return;
    }
    if (commtityType.length == 0) {
        parent.$.messager.alert('请选择商品类别');
        return;
    }
    if(commtityType.length > 5){
        parent.$.messager.alert('最多可选5个分类');
        return;
    }
    if (!/^(0|([1-9]\d*))(\.\d+)?$/.test(marketPrice) || marketPrice.length>18) {
        parent.$.messager.alert('请正确输入商品价格');
        return;
    }
    if (!/^[0-9]*$/.test(needScore) || needScore.length>9) {
        parent.$.messager.alert('请正确输入兑换积分');
        return;
    }
    if (!attributePrice) {
        if (discountPrice == "" || discountPrice == null) {
            parent.$.messager.alert('请输入优惠价格');
            return;
        } else {
            if (!/^(0|([1-9]\d*))(\.\d+)?$/.test(discountPrice) || discountPrice.length>18) {
                parent.$.messager.alert('请正确输入优惠价格');
                return;
            }
        }
    }
    if (!attributeScore) {
        if (discountScore == "" || discountScore == null) {
            parent.$.messager.alert('请输入优惠兑换积分');
            return;
        } else {
            if (!/^[0-9]*$/.test(discountScore) || discountScore.length>9) {
                parent.$.messager.alert('请正确输入优惠兑换积分');
                return;
            }
        }
    }
    if (attachedFile.length <= 0){
        parent.$.messager.alert('请至少上传一张商品图片');
        return;
    }

    var url;
    if (id == "" || id == null) {
        url = $.util.getRootPath() + '/productManage/saveProduct?dictionaryId=' + commtityType;
    } else {
        url = $.util.getRootPath() + '/productManage/editProduct?dictionaryId=' + commtityType;
    }
    var form = parent.$('#productAdd').form('submit', {
        url: url,
        onSubmit: function () {
            return parent.$('#productAdd').form('validate');
        },
        success: function (data) {
            if (data.success) {
                $('#listTable1').datagrid('reload');
                dialog.dialog('close');
            }
            $.easyui.messager.show(data.message);
        }
    });
}

